import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/utils/input_formatter_tools.dart';
import 'package:finance_app/src/widgets/button/normal_button.dart';
import 'package:finance_app/src/widgets/input/input_field.dart';
import 'package:flutter/material.dart';

import 'default_bottom_sheet.dart';

/// 添加折扣
/// delete  返回 true
/// ok 返回对应的折扣
showApplyCreditBottomSheet(BuildContext context, String currencyCode,
    {num availableCredit,
    num totalAmount,
    String creditValue,
    bool isBill}) async {
  final result = await showDefaultBottomSheet(context,
      child: ApplyCreditBottomSheet(
          currencyCode: currencyCode,
          availableCredit: availableCredit,
          totalAmount: totalAmount,
          creditValue: creditValue,
          isBill: isBill),
      title: '${S.current.available_}${availableCredit.toStringAsNotFixed(2)}',
      isScrollControlled: true,
      leading: creditValue != null
          ? DefaultBottomSheetLeadingButton(
              title: S.current.delete,
              onTap: creditValue == null
                  ? null
                  : () {
                      Navigator.of(context).pop(true);
                    },
            )
          : null);
  return result;
}

class ApplyCreditBottomSheet extends StatefulWidget {
  final String currencyCode;
  final num availableCredit;
  final num totalAmount;
  final String creditValue;
  final bool isBill;

  const ApplyCreditBottomSheet(
      {Key key,
      this.currencyCode,
      this.totalAmount,
      this.availableCredit,
      this.creditValue,
      this.isBill})
      : super(key: key);

  @override
  _ApplyCreditBottomSheetState createState() => _ApplyCreditBottomSheetState();
}

class _ApplyCreditBottomSheetState extends State<ApplyCreditBottomSheet> {
  TextEditingController creditController;
  FocusNode creditFocusNode = FocusNode();

  num creditValue = 0;

  bool isEnable = true;
  bool showExceedTotalError = false;

  void _onAdd() {
    if (creditController.text.length == 0) {
      BaseConfig.dialogBase.showToast(
          context: context, content: S.current.please_enter_credit_amount);
      return;
    }
    String returnText = '${creditController.text}';
    Navigator.of(context).pop(returnText);
  }

  @override
  void initState() {
    super.initState();
    creditController = TextEditingController(
        text: widget.creditValue ??
            widget.availableCredit.clamp(0, widget.totalAmount).toString());
    creditValue = num.tryParse(creditController.text) ?? 0;
    creditController.addListener(() {
      creditValue = num.tryParse(creditController.text) ?? 0;
      if (creditValue > widget.availableCredit) {
        String text = widget.availableCredit.toStringAsFixed(2);
        creditController.value = TextEditingValue(
          text: text,
          selection: TextSelection.collapsed(
            offset: text.length,
          ),
        );

        return;
      }
      if (creditController.text.length > 0) {
        if (creditValue > widget.totalAmount) {
          showExceedTotalError = true;
        } else {
          showExceedTotalError = false;
        }

        setState(() {
          isEnable = true;
        });
      } else {
        setState(() {
          isEnable = false;
        });
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    creditController.dispose();
    creditFocusNode.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisSize: MainAxisSize.min,
      children: [
        AppSpaces.h25,
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 45.0),
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  _buildTitleText(
                      widget.isBill
                          ? S.current.bill_amount
                          : S.current.invoice_amount,
                      false),
                  _buildAmountText(
                      '${widget.totalAmount.toStringAsFixed(2)}', false),
                ],
              ),
              AppSpaces.h10,
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  _buildTitleText(
                      S.current.credit_to_be_applied, showExceedTotalError),
                  _buildAmountText(
                      '${creditValue > 0 ? '-' : ''}${creditValue.toStringAsFixed(2)}',
                      showExceedTotalError),
                ],
              ),
            ],
          ),
        ),
        AppSpaces.h25,
        InputField(
          tip: S.current.credit_,
          controller: creditController,
          focusNode: creditFocusNode,
          hasError: showExceedTotalError,
          inputFormatters: [doubleLimit2InputFormatter],
        ),
        if (showExceedTotalError && widget.isBill)
          Padding(
            padding: const EdgeInsets.only(top: 5.0),
            child: _buildErrorText(
                S.current.credit_can_only_be_equal_or_less_than_bill_amount),
          ),
        if (showExceedTotalError && !widget.isBill)
          Padding(
            padding: const EdgeInsets.only(top: 5.0),
            child: _buildErrorText(
                S.current.credit_can_only_be_equal_or_less_than_invoice_amount),
          ),
        AppSpaces.h30,
        NormalButton(
          title: S.current.apply_credit,
          onTap: (isEnable && !showExceedTotalError) ? _onAdd : null,
        ),
      ],
    );
  }

  Widget _buildTitleText(String text, bool isError) => Text(
        text,
        textAlign: TextAlign.center,
        style: TextStyle(
          color: isError ? aceRedColor : aceBlackColor,
          fontSize: getSp(16),
          fontWeight: FontWeight.w400,
          height: 22 / 16,
        ),
      );

  Widget _buildAmountText(String text, bool isError) => Text(
        text,
        textAlign: TextAlign.center,
        style: TextStyle(
          color: isError ? aceRedColor : aceBlackColor,
          fontSize: getSp(16),
          fontWeight: FontWeight.w700,
          height: 22 / 16,
        ),
      );

  Widget _buildErrorText(String text) => Text(
        text,
        textAlign: TextAlign.center,
        style: TextStyle(
          color: aceRedColor,
          fontSize: getSp(12),
          fontWeight: FontWeight.w700,
          height: 22 / 16,
        ),
      );
}
